﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.SystemModule;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;

namespace EasyXaf.EntityDesigner.Controllers;

public class EntityPropertyViewController : ObjectViewController<ObjectView, EntityProperty>
{
    private NewObjectViewController _newObjectViewController;

    protected override void OnActivated()
    {
        base.OnActivated();

        _newObjectViewController = Frame.GetController<NewObjectViewController>();
        if (_newObjectViewController != null)
        {
            _newObjectViewController.ObjectCreated += NewObjectViewController_ObjectCreated;
        }
    }

    protected override void OnDeactivated()
    {
        if (_newObjectViewController != null)
        {
            _newObjectViewController.ObjectCreated -= NewObjectViewController_ObjectCreated;
        }

        base.OnDeactivated();
    }

    private void NewObjectViewController_ObjectCreated(object sender, ObjectCreatedEventArgs e)
    {
        if (e.CreatedObject is EntityProperty entityProperty)
        {
            entityProperty.Order = entityProperty.Entity.Properties.Max(p => p.Order) + 1;
        }
    }
}
